package com.los.rabbitmq.workFair;

import com.los.rabbitmq.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @program: rabbitmq
 * @description: 工作队列消费者
 * @author: Yujuan
 * @create: 2018-08-02 10:08
 **/
public class WorkConsumer2 {
    private static  final String QUEUE_NAME="los_work_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection= ConnectionUtils.getConnection();
        Channel channel=connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        channel.basicQos(1);//保证一次只分发一个
        //定义消费者
        DefaultConsumer consumer=new DefaultConsumer(channel){
            //消息到达 触发该方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg=new String(body,"utf-8");
                System.out.println(msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println("[1] done");
                    //手动回执一个消息
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };
        //关闭自动应答
        boolean autoAck=false;
        channel.basicConsume(QUEUE_NAME,autoAck,consumer);
    }
}
